package com.wzxl.config.filter;

import com.wzxl.service.BaseService;
import com.wzxl.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.NamedThreadLocal;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;

/**
 * @author rxbyes
 * @version V1.0
 * @package com.wzxl.config.filter
 * @description: TODO ( 日志拦截 )
 * @date 2017 上午10:00
 */
@Configuration
public class ApiFilter extends BaseService implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApiFilter.class);

    private static final ThreadLocal<Long> START_TIME_THREADLOCAL = new NamedThreadLocal<Long>("ThreadLocal StartTime");

    private static final String REQUEST_TIME_FORMAT = "hh:mm:ss.SSS";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) {
         SimpleDateFormat dateFormat = new SimpleDateFormat(REQUEST_TIME_FORMAT);
        long begintime = System.currentTimeMillis();
        START_TIME_THREADLOCAL.set(begintime);
            LOGGER.debug("开始计时：{} URL：{}", dateFormat.format(begintime), request.getRequestURI());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) {
        if (!StringUtils.isEmpty(modelAndView)) {
            LOGGER.info("请求视图地址：{}", modelAndView.getViewName());
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        /**
         *  记录日志，持久化过程，需要完成
         */
//        if (LOGGER.isDebugEnabled()) {
        /**
         * 得到线程绑定的局部变量，开始时间，并且减去结束时间
         */
        long beginTime = START_TIME_THREADLOCAL.get();
        long endTime = System.currentTimeMillis();

        LOGGER.info("结束计时：{}，耗时：{}，URL：{},最大内存：{}m，已分配内存中剩余空间：{}m，最大可用内存：{}m",
                StringUtil.formatDateTime(endTime - beginTime),
                request.getRequestURI(), Runtime.getRuntime().maxMemory() / 1024 / 1024,
                Runtime.getRuntime().totalMemory() / 1024 / 1024,
                Runtime.getRuntime().freeMemory() / 1024 / 1024,
                (Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory() + Runtime.getRuntime().freeMemory()) / 1024 / 1024);
        /**
         * 删除线程变量中的数据，防止内存泄露
         */
        START_TIME_THREADLOCAL.remove();
    }


}
